import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_trip/dao/travel_dao.dart';
import 'package:flutter_trip/model/travel_model.dart';
import 'package:flutter_trip/util/navigator_util.dart';
import 'package:flutter_trip/widget/loading_container.dart';
import 'package:flutter_trip/widget/webview.dart';
// import 'package:flutter_trip/pages/travel_tab_page.dart';

const PAGE_SIZE = 10; //每页显示的大小
const _TRAVEL_URL =
    'https://m.ctrip.com/restapi/soa2/16189/json/searchTripShootListForHomePageV2?_fxpcqlniredt=09031014111431397988&__gw_appid=99999999&__gw_ver=1.0&__gw_from=10650013707&__gw_platform=H5';

//旅拍tab页面
class TravelTabPage extends StatefulWidget {
  final String travelUrl;
  final String groupChanneCode;

  const TravelTabPage({Key key, this.travelUrl, this.groupChanneCode})
      : super(key: key);
  @override
  _TravelTabPageState createState() => _TravelTabPageState();
}

// AutomaticKeepAliveClientMixin 实现页面不重新绘制
class _TravelTabPageState extends State<TravelTabPage>
    with AutomaticKeepAliveClientMixin {
  List<TravelItem> travelItem;
  int pageIndex = 1;
  bool _loading = true; //加载
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData(loadMore: true);
      }
    });
    _loadData();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  //初始化tab数据
  void _loadData({loadMore = false}) async {
    try {
      if (loadMore) {
        pageIndex++;
      } else {
        pageIndex = 1;
      }
      TravelModel model = await TravelDao.fetch(widget.travelUrl ?? _TRAVEL_URL,
          widget.groupChanneCode, pageIndex, PAGE_SIZE);

      setState(() {
        List<TravelItem> items = _filterItems(model.resultList);
        if (travelItem != null) {
          travelItem.addAll(items);
        } else {
          travelItem = items;
        }
        _loading = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
  }

  // 过滤数据方法
  List<TravelItem> _filterItems(List<TravelItem> resultList) {
    if (resultList == null) {
      return [];
    }
    List<TravelItem> filterItem = [];
    resultList.forEach((item) {
      if (item.article != null) {
        filterItem.add(item);
      }
    });

    return filterItem;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LoadingContain(
        cover: true,
        isLoading: _loading,
        child: RefreshIndicator(
          child: MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child: StaggeredGridView.countBuilder(
              // 添加滚动控制
              controller: _scrollController,
              crossAxisCount: 4,
              itemCount: travelItem?.length ?? 0,
              itemBuilder: (BuildContext context, int index) =>
                  _travelItem(index, travelItem[index]),
              staggeredTileBuilder: (int index) => new StaggeredTile.fit(2),
            ),
          ),
          onRefresh: _handleRefresh,
        ),
      ),
    );
  }

  _travelItem(int index, TravelItem item) {
    return GestureDetector(
      onTap: () {
        if (item.article.urls != null && item.article.urls.length > 0) {
          NavigatorUtil.push(
              context,
              WebView(
                url: item.article.urls[0].h5Url,
                title: '详情',
              ));
        }
      },
      child: Card(
        child: PhysicalModel(
          color: Colors.transparent,
          clipBehavior: Clip.antiAlias,
          borderRadius: BorderRadius.circular(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _itemImage(item),
              Container(
                padding: EdgeInsets.all(4),
                child: Text(
                  item.article.articleTitle,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 14, color: Colors.black87),
                ),
              ),
              _infoText(item)
            ],
          ),
        ),
      ),
    );
  }

  _infoText(TravelItem item) {
    return Container(
      padding: EdgeInsets.fromLTRB(6, 0, 6, 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              // 实现圆角
              PhysicalModel(
                color: Colors.transparent,
                clipBehavior: Clip.antiAlias,
                borderRadius: BorderRadius.circular(12),
                child: Image.network(
                  item.article.author?.coverImage?.dynamicUrl,
                  width: 24,
                  height: 24,
                ),
              ),
              Container(
                padding: EdgeInsets.all(5),
                width: 90,
                child: Text(
                  item.article.author?.nickName,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 12),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Icon(
                Icons.thumb_up,
                size: 14,
                color: Colors.grey,
              ),
              Padding(
                padding: EdgeInsets.only(left: 3),
                child: Text(
                  item.article.likeCount.toString(),
                  style: TextStyle(fontSize: 10),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  // item 图片
  _itemImage(TravelItem item) {
    return Stack(
      children: [
        Image.network(item.article.images[0]?.dynamicUrl),
        Positioned(
          bottom: 8,
          left: 8,
          child: Container(
            padding: EdgeInsets.fromLTRB(5, 1, 5, 1),
            decoration: BoxDecoration(
              color: Colors.black54,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Row(
              children: [
                Padding(
                  padding: EdgeInsets.only(right: 3),
                  child: Icon(
                    Icons.location_on,
                    color: Colors.white,
                    size: 12,
                  ),
                ),
                LimitedBox(
                  maxWidth: 130,
                  child: Text(
                    _poiName(item),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.white, fontSize: 12),
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  // 位置信息判空
  String _poiName(TravelItem item) {
    return item.article.pois == null || item.article.pois.length == 0
        ? '未知'
        : item.article.pois[0]?.poiName ?? '未知';
  }

  // 重新AutomaticKeepAliveClientMixin 的方法
  @override
  bool get wantKeepAlive => true;
  // 下拉刷新
  Future<Null> _handleRefresh() async {
    _loadData();
    return null;
  }
}
